/**
 * User: Mariano Rico
 * Date: 04-ene-2006
 * Time: 17:52:18
 */

/*
The main idea of this Class is to handle a file like this one foaf.200506.03.rdf
(obtained from http://xmlns.com/foaf/0.1/20050603.rdf) in order to obtain information as:
 - Namespaces
 - Classes defined
 - Properties defined
 With all this information we will written to a file using wiki (JSPWiki) notation.
*/
package fortunata.fswapps.omemo.util;
import java.util.*;
import java.io.*;

import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.plugin.*;
import org.apache.log4j.Logger;
import fortunata.fswapps.omemo.InfoExtractor;
import fortunata.fswapps.omemo.OntologyWikiPageName;
import fortunata.util.NiceDate;
import fortunata.FortunataPlugin;
import fortunata.fswapps.omemo.util.AnalyzerRDFStart;
import fortunata.util.FileDownloader;

public class AnalyzerRDF extends FortunataPlugin implements WikiPlugin {
       private static Logger log = Logger.getLogger( AnalyzerRDF.class );
       private final String wikiFileExtension = ".txt";
//    static Timer timer = new Timer();
//    {timer.scheduleAtFixedRate(new TimerTask(), 1000L, 1000L);}
//    static long lastCheck = 0;
//    long checkInterval = 1000 * 10; // 1 min = 1000 ms * 60

    public String execute (WikiContext context, Map parameterMap) throws PluginException{
        /**** take care of a missing parameterMap (may that ever happen?) ****/
        String ErrorStringNP = "No parameters given";
        if (parameterMap == null) {
           return ErrorStringNP;
        }
        String alias       = FormManager.getFieldNoEmplyValue("alias",       parameterMap, "alias");
        String altURL      = FormManager.getFieldNoEmplyValue("altURL",      parameterMap, "URL");
        String ns          = FormManager.getFieldNoEmplyValue("ns",          parameterMap, "namespace");
        String ontLang     = FormManager.getFieldNoEmplyValue("ontLang",     parameterMap, "ontoly language");
        String versionDate = FormManager.getFieldNoEmplyValue("versionDate", parameterMap, "version date");

        OntologyWikiPageName owpn = new OntologyWikiPageName(alias.toUpperCase(), versionDate);
        owpn.reasignPrefix(AnalyzerRDFStart.getPrefix());
        String ontologyWikiPageName = owpn.getOntologyWikiPageName();

        String link = context.getEngine().getViewURL(ontologyWikiPageName);
        String workDir = getWorkDir (context);
        String checkString = null;

        String rdfFileNameWithPath = workDir + File.separator + owpn.toFileName();
//        long now = new Date().getTime();
//        if (now > lastCheck + checkInterval){
           checkString = checkUpdates(rdfFileNameWithPath, altURL);
//           lastCheck = now;
//           //System.out.println(lastCheck +","+checkInterval+","+now);
//        }else {
//            checkString = "checked " +niceDateIntervalTillNow(new Date(lastCheck));
//        }

        if (AnalyzerRDFStart.mustGenerate()){
            FileOutputStream fos = null;
            FileInputStream fis = null;
            try {
               //String wikiFilesExtension = Context.getEngine().getWikiProperties().getProperty(...
               fos = new FileOutputStream(workDir + File.separator + ontologyWikiPageName + wikiFileExtension);
               fis = new FileInputStream(rdfFileNameWithPath); //Read from working directory
               //log.info("Created file: " + rdfFileNameWithPath);

               //Extract information
               InfoExtractor infoe = new InfoExtractor(fis, ns, ontLang);
               infoe.writePage(workDir,
                               owpn,
                               AnalyzerRDFStart.getChecksWikiPageName());
               fis.close();
               fos.close();
            }catch(Exception e){
               e.printStackTrace(System.out);
               throw new PluginException(e.getMessage());
            }
        }
        return   "<TR>" +
                     "<TD>"+ owpn.toFileName() + "<BR> ("+ checkString + ")"+ "</TD>"+
                     "<TD><A href='"+link+"'>"+ontologyWikiPageName +"</A></TD>"+
                     "<TD><A href='"+altURL+"'>"+altURL+"</A></TD>"+
                     "<TD>"+ ns +"</TD>"+
                     "<TD>"+ ontLang +"</TD>"+
                 "</TR>";
    }

    /**
     * If you have Internet access, it checks the file stored at altURL against the file fullFileName. If they
     * differ, the remote file replaces the local one.  A nice message is returned.
     * If you don't have Internet access, you will get the message "No Internet".
     * Only if you have Internet access references will be checked/downloaded
     * @param fullFileName
     * @param altURL points to a remote file
     * @return a descriptive string
     * @throws com.ecyrd.jspwiki.plugin.PluginException
     */
    private String checkUpdates(String fullFileName, String altURL) throws PluginException {
        String checkString;
        File f = new File(fullFileName);
        FileDownloader fdl = null;
        if (!FileDownloader.canWeConnectToInternet()){
            checkString = "No Internet";
            return checkString;
        }
        try {
            fdl = new FileDownloader(altURL);
            if (!f.exists()){  //If file doesn't exists
               fdl.copyToFile(fullFileName);
               checkString = "Created just now";
            }else {   //If file exists
               File fok = new File(fullFileName);
               Date lastMod = new Date(fok.lastModified());
               //Check are equal
               if (fdl.hasSameContent(fullFileName)){
                   checkString = "Last update: " + niceDateIntervalTillNow(lastMod);
               }else { //They have different content
                  fdl.copyToFile(fullFileName);
                  checkString = "Updated now (after " + niceDateIntervalTillNow(lastMod) + ")";
               }
            }
        } catch(Exception e){
            throw new PluginException(e.getMessage());
        }
        return checkString;
    }

    public static String niceDateIntervalTillNow(Date from){
        return niceDateInterval(from, new Date());
    }
    public static String niceDateInterval(Date from, Date to){
        return NiceDate.niceDateInterval(from,  to);
    }

}
